package gestores;

import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import dados.Noticia;

public class ReadXMLNews {

	private URL url;
	private ArrayList <Noticia> noticias;

	public ReadXMLNews(URL u){
		this.url = u;
	}

	public ArrayList <Noticia> init(){
		noticias = new ArrayList <Noticia>();
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(url.openStream());
			doc.getDocumentElement().normalize();
			//			System.out.println(doc);

			//			System.out.println("root of xml file " + doc.getDocumentElement().getNodeName());

			NodeList nodes = doc.getElementsByTagName("item");
			//			System.out.println("Nodes : " + nodes);
			//			System.out.println("Noticias ==========================");
			//			System.out.println("Nodes lenght: " + nodes.getLength());

			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);

				if (node.getNodeType() == Node.ELEMENT_NODE) {					
					Element element = (Element) node;
					Noticia noticia = new Noticia();
					noticia.setTitulo(getValue("title", element));
					if(!getValue("description", element).isEmpty())
						noticia.setDescricao(getValue("description", element));
					noticia.setLink(getValue("link", element));
					if(getValue("pubDate", element) != null)
						noticia.setPubDate(getValue("pubDate", element));

					noticias.add(noticia);
				}		
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return noticias;
	}

	private static String getValue(String tag, Element element) {
		NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
		Node node = (Node) nodes.item(0);
		if(node != null)
			return node.getNodeValue();
		return "Sem campo a apresentar";

	}
}
